package com.ytrsoft;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MySQL implements Connectable {

    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final Logger logger = LogManager.getLogger(MySQL.class);

    private final String host;

    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            logger.error("{}", e.getMessage());
        }
    }

    public MySQL(String host) {
        this.host = host;
        logger.info("启动 {}", host);
    }

    @Override
    public boolean isConnected(String username, String password)  {
        Connection connection = null;
        try {
            String URL = "jdbc:mysql://" + host + ":3306/";
            connection = DriverManager.getConnection(URL, username, password);
            return true;
        } catch (Exception e) {
            logger.error("{}", e.getMessage());
        }  finally {
           if (connection != null) {
               try {
                   connection.close();
               } catch (SQLException e) {
                   logger.error("{}", e.getMessage());
               }
           }
        }
        return false;
    }
}